import type { Task, SubTask } from '../types/project';
import { TaskStatus, TaskPriority } from '../types/project';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';

dayjs.extend(isBetween);

/**
 * 任务相关的工具函数集合
 */

/**
 * 计算任务进度百分比
 * @param subTasks 子任务列表
 * @returns 进度百分比 (0-100)
 */
export const calculateTaskProgress = (subTasks: SubTask[]): number => {
  if (subTasks.length === 0) return 0;
  const completedCount = subTasks.filter(st => st.completed).length;
  return Math.round((completedCount / subTasks.length) * 100);
};

/**
 * 检查任务是否已过期
 * @param task 任务对象
 * @returns 是否过期
 */
export const isTaskOverdue = (task: Task): boolean => {
  if (!task.dueDate) return false;
  return dayjs().isAfter(dayjs(task.dueDate)) && task.status !== TaskStatus.COMPLETED;
};

/**
 * 获取任务剩余天数
 * @param dueDate 截止时间
 * @returns 剩余天数，负数表示已过期
 */
export const getTaskRemainingDays = (dueDate?: string): number | null => {
  if (!dueDate) return null;
  return dayjs(dueDate).diff(dayjs(), 'day');
};

/**
 * 获取任务状态的显示文本和颜色
 * @param status 任务状态
 * @returns 状态信息对象
 */
export const getTaskStatusInfo = (status: TaskStatus) => {
  const statusMap = {
    [TaskStatus.NOT_STARTED]: {
      text: '未开始',
      color: '#d9d9d9',
      bgColor: '#f5f5f5',
      className: 'status-not-started'
    },
    [TaskStatus.IN_PROGRESS]: {
      text: '进行中',
      color: '#1890ff',
      bgColor: '#e6f7ff',
      className: 'status-in-progress'
    },
    [TaskStatus.COMPLETED]: {
      text: '已完成',
      color: '#52c41a',
      bgColor: '#f6ffed',
      className: 'status-completed'
    },
  };
  return statusMap[status];
};

/**
 * 获取任务优先级的显示文本和颜色
 * @param priority 任务优先级
 * @returns 优先级信息对象
 */
export const getTaskPriorityInfo = (priority: TaskPriority) => {
  const priorityMap = {
    [TaskPriority.LOW]: {
      text: '低优先级',
      shortText: '低',
      color: '#87d068',
      bgColor: '#f6ffed',
      className: 'priority-low'
    },
    [TaskPriority.MEDIUM]: {
      text: '中优先级',
      shortText: '中',
      color: '#108ee9',
      bgColor: '#e6f7ff',
      className: 'priority-medium'
    },
    [TaskPriority.HIGH]: {
      text: '高优先级',
      shortText: '高',
      color: '#f50',
      bgColor: '#fff2e8',
      className: 'priority-high'
    },
    [TaskPriority.URGENT]: {
      text: '紧急',
      shortText: '紧急',
      color: '#ff4d4f',
      bgColor: '#fff1f0',
      className: 'priority-urgent'
    },
  };
  return priorityMap[priority];
};

/**
 * 格式化日期显示
 * @param dateString 日期字符串
 * @param format 格式化模板，默认为 'YYYY-MM-DD'
 * @returns 格式化后的日期字符串
 */
export const formatDate = (dateString?: string, format: string = 'YYYY-MM-DD'): string => {
  if (!dateString) return '';
  return dayjs(dateString).format(format);
};

/**
 * 格式化相对时间显示
 * @param dateString 日期字符串
 * @returns 相对时间字符串（如：2天前、3小时前）
 */
export const formatRelativeTime = (dateString: string): string => {
  const now = dayjs();
  const date = dayjs(dateString);
  const diffDays = now.diff(date, 'day');
  const diffHours = now.diff(date, 'hour');
  const diffMinutes = now.diff(date, 'minute');

  if (diffDays > 0) {
    return `${diffDays}天前`;
  } else if (diffHours > 0) {
    return `${diffHours}小时前`;
  } else if (diffMinutes > 0) {
    return `${diffMinutes}分钟前`;
  } else {
    return '刚刚';
  }
};

/**
 * 获取截止时间的显示样式类名
 * @param dueDate 截止时间
 * @param status 任务状态
 * @returns CSS 类名
 */
export const getDueDateClassName = (dueDate?: string, status?: TaskStatus): string => {
  if (!dueDate) return 'text-gray-500';
  if (status === TaskStatus.COMPLETED) return 'text-gray-500';

  const remainingDays = getTaskRemainingDays(dueDate);
  if (remainingDays === null) return 'text-gray-500';

  if (remainingDays < 0) return 'text-red-500 font-medium'; // 已过期
  if (remainingDays <= 1) return 'text-red-500'; // 今天或明天到期
  if (remainingDays <= 3) return 'text-orange-500'; // 3天内到期
  return 'text-gray-500';
};

/**
 * 根据筛选条件过滤任务
 * @param tasks 任务列表
 * @param filters 筛选条件
 * @returns 过滤后的任务列表
 */
export const filterTasks = (tasks: Task[], filters: any): Task[] => {
  return tasks.filter(task => {
    // 状态筛选
    if (filters.status && filters.status.length > 0 && !filters.status.includes(task.status)) {
      return false;
    }

    // 优先级筛选
    if (filters.priority && filters.priority.length > 0 && !filters.priority.includes(task.priority)) {
      return false;
    }

    // 负责人筛选
    if (filters.assignee && filters.assignee.length > 0) {
      if (!task.assignee || !filters.assignee.includes(task.assignee.id)) {
        return false;
      }
    }

    // 里程碑筛选
    if (filters.milestone && filters.milestone.length > 0) {
      if (!task.milestone || !filters.milestone.includes(task.milestone)) {
        return false;
      }
    }

    // 搜索筛选
    if (filters.search && filters.search.trim()) {
      const searchTerm = filters.search.toLowerCase();
      if (!task.title.toLowerCase().includes(searchTerm) &&
        !task.description?.toLowerCase().includes(searchTerm)) {
        return false;
      }
    }

    // 开始时间筛选
    if (filters.startDate && filters.startDate.length === 2) {
      if (!task.startDate) return false;
      const taskStartDate = dayjs(task.startDate);
      const filterStart = dayjs(filters.startDate[0]);
      const filterEnd = dayjs(filters.startDate[1]);
      if (!taskStartDate.isBetween(filterStart, filterEnd, 'day', '[]')) {
        return false;
      }
    }

    // 截止时间筛选
    if (filters.dueDate && filters.dueDate.length === 2) {
      if (!task.dueDate) return false;
      const taskDueDate = dayjs(task.dueDate);
      const filterStart = dayjs(filters.dueDate[0]);
      const filterEnd = dayjs(filters.dueDate[1]);
      if (!taskDueDate.isBetween(filterStart, filterEnd, 'day', '[]')) {
        return false;
      }
    }

    return true;
  });
};

/**
 * 根据排序条件对任务进行排序
 * @param tasks 任务列表
 * @param sortField 排序字段
 * @param sortOrder 排序顺序
 * @returns 排序后的任务列表
 */
export const sortTasks = (
  tasks: Task[],
  sortField: string,
  sortOrder: 'asc' | 'desc'
): Task[] => {
  const sortedTasks = [...tasks].sort((a, b) => {
    let aValue: any;
    let bValue: any;

    switch (sortField) {
      case 'title':
        aValue = a.title.toLowerCase();
        bValue = b.title.toLowerCase();
        break;
      case 'status':
        // 按状态排序：未开始 < 进行中 < 已完成
        const statusOrder = {
          [TaskStatus.NOT_STARTED]: 0,
          [TaskStatus.IN_PROGRESS]: 1,
          [TaskStatus.COMPLETED]: 2,
        };
        aValue = statusOrder[a.status];
        bValue = statusOrder[b.status];
        break;
      case 'priority':
        // 按优先级排序：紧急 > 高 > 中 > 低
        const priorityOrder = {
          [TaskPriority.URGENT]: 3,
          [TaskPriority.HIGH]: 2,
          [TaskPriority.MEDIUM]: 1,
          [TaskPriority.LOW]: 0,
        };
        aValue = priorityOrder[a.priority];
        bValue = priorityOrder[b.priority];
        break;
      case 'dueDate':
        aValue = a.dueDate ? dayjs(a.dueDate).valueOf() : 0;
        bValue = b.dueDate ? dayjs(b.dueDate).valueOf() : 0;
        break;
      case 'createdAt':
        aValue = dayjs(a.createdAt).valueOf();
        bValue = dayjs(b.createdAt).valueOf();
        break;
      case 'updatedAt':
        aValue = dayjs(a.updatedAt).valueOf();
        bValue = dayjs(b.updatedAt).valueOf();
        break;
      default:
        return 0;
    }

    if (aValue < bValue) {
      return sortOrder === 'asc' ? -1 : 1;
    }
    if (aValue > bValue) {
      return sortOrder === 'asc' ? 1 : -1;
    }
    return 0;
  });

  return sortedTasks;
};

/**
 * 生成任务的唯一ID
 * @param prefix 前缀，默认为 'task'
 * @returns 唯一ID字符串
 */
export const generateTaskId = (prefix: string = 'task'): string => {
  return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};

/**
 * 生成子任务的唯一ID
 * @returns 唯一ID字符串
 */
export const generateSubTaskId = (): string => {
  return generateTaskId('subtask');
};

/**
 * 生成卡片的唯一ID
 * @returns 唯一ID字符串
 */
export const generateCardId = (): string => {
  return generateTaskId('card');
};

/**
 * 计算分组内任务的统计信息
 * @param tasks 任务列表
 * @returns 统计信息对象
 */
export const getTaskGroupStats = (tasks: Task[]) => {
  const stats = {
    total: tasks.length,
    notStarted: 0,
    inProgress: 0,
    completed: 0,
    overdue: 0,
    progress: 0,
  };

  tasks.forEach(task => {
    switch (task.status) {
      case TaskStatus.NOT_STARTED:
        stats.notStarted++;
        break;
      case TaskStatus.IN_PROGRESS:
        stats.inProgress++;
        break;
      case TaskStatus.COMPLETED:
        stats.completed++;
        break;
    }

    if (isTaskOverdue(task)) {
      stats.overdue++;
    }
  });

  // 计算完成进度
  stats.progress = stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0;

  return stats;
};

/**
 * 验证任务数据的有效性
 * @param task 任务对象
 * @returns 验证结果对象
 */
export const validateTask = (task: Partial<Task>) => {
  const errors: string[] = [];

  if (!task.title || task.title.trim().length === 0) {
    errors.push('任务标题不能为空');
  }

  if (task.title && task.title.length > 100) {
    errors.push('任务标题不能超过100个字符');
  }

  if (task.description && task.description.length > 500) {
    errors.push('任务描述不能超过500个字符');
  }

  if (task.startDate && task.dueDate) {
    if (dayjs(task.dueDate).isBefore(dayjs(task.startDate))) {
      errors.push('截止时间不能早于开始时间');
    }
  }

  return {
    isValid: errors.length === 0,
    errors,
  };
};
